import layout_compiler
import os.path

class HtmlEditor(object):
  def __init__(self):
    self.window = layout_compiler.compile(file("test_data/Html_editor.txt").read())
    
    self.text = ""
    self.search_text = ""
    self.selection = "(0,0)"
    self.filename = "/dev/null"

  def start(self, filename=None):
    self.window.when_changed('html_win', self.text_changed)
    self.window.when_changed('filename', self.filename_changed)
    self.window.when_changed('new', self.new)
    self.window.when_changed('open', self.open)
    self.window.when_changed('save', self.save)
    self.window.when_changed('search', self.search)
    self.window.when_changed('next', self.next)
    self.window.when_changed('selected', self.selection_changed)
    d = {}
    if filename is not None:
      d['filename'] = filename
      self.filename = filename
    self.window(d)

  def text_changed(self, old, new):
    self.text = new

  def filename_changed(self, old, new):
    self.filename = new

  def new(self, old, new):
    if new == 1:
      self.window.update('html_win', "")
      self.window.update('filename', "/dev/null")

  def open(self, old, new):
    if new == 1:
      if os.path.isfile(self.filename):
        self.window.update('html_win', file(self.filename).read())
        self.window.update("status", "Open success")
        self.window.update("error", False)
      else:
        self.window.update("status", "File '%s' does not exist" % self.filename)
        self.window.update("error", True)

  def save(self, old, new):
    if new == 1:
      try:
        file(self.filename, "w").write(self.text)
        self.window.update("status", "Save success")
      except:
        self.window.update("status", "Couldn't save file to %s" % self.filename)

  def search(self, old, new):
    self.search_text = new

  def selection_changed(self, old, new):
    self.selection = new

  def next(self, old, new):
    if new == 1:
      if not self.search_text:
        return
      sstart, send = (int(x) for x in self.selection[1:-1].split(","))
      found = self.text.find(self.search_text, send)
      if found < 0:
        return
      self.window.update("selected", "(%d,%d)" % (found, found + len(self.search_text)))

if __name__ == "__main__":
  import sys
  if len(sys.argv) == 2:
    HtmlEditor().start(sys.argv[1])
  else:
    HtmlEditor().start()
